<?php


namespace app\admin\service;


use app\admin\model\Tag as TagModel;
use think\Db;

class TagService
{
    protected $model;
    protected $tagArticle;
    public function __construct()
    {
        $this->model = app()->make(TagModel::class);
        $this->tagArticle = app()->make(TagArticleService::class);
    }

    public function add($tag, $aid) {
        if (empty($tag)) {
            return;
        }
        $tagArr = explode(",", $tag);
        foreach($tagArr as $key=>$tagName) {
            $tid = $this->getTagId($tagName);
            if ($tid > 0) {
                $data[] = $tid;
                $this->saveArticleTag($aid, $data);
            }
        }
    }

    /**
     * 获取tagId
     *
     * @param $tagName
     * @return int|string
     */
    public function getTagId ($tagName) {
        $tagData = $this->model->where(array("name"=>$tagName))->find();
        if (empty($tagData)) {
            $data['name'] = $tagName;
            return $this->model->insertGetId($data);
        }
        return $tagData['id'];
    }

    /**
     * 保存文章标签
     *
     * @param $aid
     * @param $data
     */
    public function saveArticleTag($aid, $data) {
        $where = 'aid=' .$aid. ' and tid not in ('.implode(',', $data). ')';
        $this->tagArticle->delete($where);
        $allData = array();
        foreach ($data as $key=>$value) {
            $newData['aid'] = $aid;
            $newData['tid'] = $value;
            $articleTag = $this->tagArticle->queryOne($newData);
            if (empty($articleTag)) {
                $allData[] = $newData;
            }
        }
        if (empty($allData)) {
            return;
        }
        $this->tagArticle->insertAll($allData);
    }

    /**
     * @return int
     * @throws \think\db\exception\DbException
     */
    public function queryCount(): int{
        return $this->model->count();
    }
}